package cn.stronglink.esm27.collection.iot.devices.esm27.task;

import java.io.IOException;
import java.util.Date;
import java.util.Timer;

import javax.annotation.Resource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import cn.stronglink.esm27.collection.iot.devices.esm27.ESM27Server;
import cn.stronglink.esm27.collection.iot.devices.esm27.request.entity.ESM27RequestMessageFactory;

/**
 * 自动推送传感器数据的任务
 * 
 * @author yuzhantao
 *
 */
@Component("autoPushSensorDataTask")
@Lazy(false)
@EnableScheduling
public class AutoPushSensorDataTask implements SchedulingConfigurer {
	private static Logger logger = LogManager.getLogger(AutoPushSensorDataTask.class.getName());
	private static final int SEND_DATA_SPAN_MILLISECOND=3000;
	private static final int DEVICE_COUNT = 2; // 设备数量
	private static final String DEFAULT_CRON = "0/5 * * * * ? ";
	private String cron = DEFAULT_CRON;
	@Resource
	private ESM27Server esm27Server; // esm27服务器

	private boolean isRun = true;

	private Timer timer;
	/**
	 * 获取任务执行规则
	 * 
	 * @return
	 */
	public String getCron() {
		return cron;
	}

	/**
	 * 设置任务执行规则
	 * 
	 * @param cron
	 */
	public void setCron(String cron) {
		if (cron == null || cron.isEmpty()) {
			isRun = false;
		} else {
			this.cron = cron;
			isRun = true;
		}
	}

	/**
	 * 定时获取传感器实时数据的任务
	 * 
	 * @throws IOException
	 */
//	@Scheduled(cron = "0/5 * * * * ?")
	protected void getSensorRealtimeDataTask(byte deviceAddress) throws IOException {
		if (esm27Server.isConnection()) {
			byte[] datas = ESM27RequestMessageFactory.createMessage(deviceAddress, (byte) 0x0A, null);
			esm27Server.send(datas);
			logger.info("定时获取传感器实时数据命令已发送");
		}
	}

	@Override
	public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
		taskRegistrar.addTriggerTask(new Runnable() {
			@Override
			public void run() {
				if (isRun == false)
					return;
				
				if(timer!=null) {
					timer.cancel();
				}
				timer = new Timer();
				
				int i=0;
				// 发送获取气体请求到i个设备
				for (i = 0; i < DEVICE_COUNT; i++) {
					timer.schedule(new PushGasTimer(esm27Server,(byte)i), i*SEND_DATA_SPAN_MILLISECOND);
				}
				// 发送风力请求
				timer.schedule(new PushWindTimer(esm27Server), i*SEND_DATA_SPAN_MILLISECOND);
			}
		}, new Trigger() {
			@Override
			public Date nextExecutionTime(TriggerContext triggerContext) {
				// 任务触发，可修改任务的执行周期
				CronTrigger trigger = new CronTrigger(cron);
				Date nextExec = trigger.nextExecutionTime(triggerContext);
				return nextExec;
			}
		});
	}
}
